var selectedTest=0;
var testCount = 1;

/*编辑试卷信息按钮*/
function editTestPaperMessage() {
    $("#editingTestPaperName").val("");
    var testPaperName = $("#testPaperName").text();
    $('#editingTestPaperName').attr("placeholder", testPaperName);
    UE.getEditor('editor');

}

/*编辑试卷信息完成按钮*/
function finishTestpaperMessage() {
    var testPaperText = $("#editingTestPaperName").val();
    if(""!=testPaperText.trim()){
        $("#testPaperName").text(testPaperText);
        $("input[name='testName']").val(testPaperText);
    }else{
        $("input[name='testName']").val("新建试卷");
    }
    var selectOprion = $("#subject").find("option:selected");
    $("#testPaperSubject").text(selectOprion.val()).attr("tag",selectOprion.attr("tag"));

    $("input[name='subject']").val(selectOprion.val());
    $("input[name='testpaperDesc']").val(UE.getEditor('editor').getContent());

}

/*筛选条件显示*/
function tagManage(chooseSubjectId,chooseCategoryId) {
    var categoryTags = $(".tag_category");
    for (var j = 0; j < categoryTags.length; j++) {
        var catlength = $(categoryTags[j]).find("a").length;
        for (var i = 0; i < catlength; i++) {
            var categoryTag = $($(categoryTags[j]).find("a")[i]).attr("tag");
            if (categoryTag == chooseCategoryId) {
                $($(categoryTags[j]).find("span")[i]).attr("class", "tag active");
            } else {
                $($(categoryTags[j]).find("span")[i]).attr("class", "tag");
            }
        }
    }


    var subjectTags = $(".tag_subject");
    var subjectActiveTag = "0";
    for (j = 0; j < subjectTags.length; j++) {
        var sublength = $(subjectTags[j]).find("a").length;
        for (i = 0; i < sublength; i++) {
            var subjectTag = $($(subjectTags[j]).find("a")[i]).attr("tag");
            if (subjectTag == chooseSubjectId) {
                $($(subjectTags[j]).find("span")[i]).attr("class", "tag active");
                subjectActiveTag = subjectTag;
            } else {
                $($(subjectTags[j]).find("span")[i]).attr("class", "tag ");
            }
        }
    }

    var active = $(".tag.active > a");
    var addSpan = "";
    var breadcrumb = $(".breadcrumb .title");

    if (subjectActiveTag != 0) {
        for (i = 0; i < 2; i++) {
            if ($($(active[i]).find("a")[0]).attr("tag") != 0) {
                if (i == 0) {
                    addSpan += '<span class="title">已选择条件：</span><span class="name">' + $(active[i]).html()
                        + '<a href="javascript:void(0);" class="breadcrumb_subject">x</a></span>';
                } else {
                    addSpan += '<span class="name">' + $(active[i]).html()
                        + '</span>';
                }
            }
            if (i < 1) {
                addSpan += '<span class="divider"> / </span>';
            }
        }
        breadcrumb.html(addSpan);

    } else {
        addSpan = '<span class="title">已选择条件：</span><span class="name">' + $(active[1]).html()
            + '</span>';
        breadcrumb.html(addSpan);

    }
    $('.breadcrumb_subject').click(function () {
        var category =$(".tag_category > .tag.active >a").attr("tag");
        toPageTestList("0",category,1);
    });

}
/*使用ajax去某个页面*/
function ajaxTopage(page) {
    var category =$(".tag_category > .tag.active >a").attr("tag");
    var subject =$(".tag_subject > .tag.active >a").attr("tag");
    toPageTestList(subject,category,page);
}

$(document).ready(function () {
    subjectService.allSubject(allSubject);
    testCategoryService.allTestCategory(allCategory);
/*    showMessage("test","测试",'notice');
    showMessage("test","测试",'error');
    showMessage("test","测试",'info');
    showMessage("test","测试",'success');*/

});

var stack_topleft = {"dir1": "down", "dir2": "right", "push": "top"};
/*提示框 */
function showMessage(title,msg,level) {
    $.pnotify.defaults.styling = "bootstrap3";
    var opts = {
        title: title,
        text: msg,
        closer: false,
        sticker: false,
        addclass: "stack-topleft",
        stack: stack_topleft
    };
    switch (level) {
        case 'error':
            opts.title = title;
            opts.text = msg;
            opts.type = "error";
            break;
        case 'info':
            opts.title = title;
            opts.text = msg;
            opts.type = "info";
            break;
        case 'success':
            opts.title = title;
            opts.text = msg;
            opts.type = "success";
            break;
    }
    var notice = $.pnotify(opts).click(function() {
        notice.pnotify_remove();
    });
}

/*dwr获取所有分类*/
function allCategory(categories) {
    var li = "";
    var tag_span = '';
    var nav_li ='';
    var docs_section = '';
    for (var i = 0; i < categories.length; i++) {
        li = li +
            '<li><a href="javascript:void(0);" class="openTheTests" tag="' + categories[i].id + '">'
            + categories[i].type + "</a></li>";
        tag_span =
            tag_span + '<span class="tag "><a href="javascript:void(0);"  tag="' + categories[i].id + '">' + categories[i].type + '</a></span>';

        nav_li += '<li id="selectAffix'+categories[i].id+'" class=""><a onclick="changeHref(this);return false" href="#categorySection'+categories[i].id+'">'+categories[i].type
            +'&nbsp;&nbsp;<span class="categoryScore'+categories[i].id+'"></span> <span class="badge badge-info" id="badge'+categories[i].id+'" style="float: right;font-weight:normal;">0</span></a></li>';

        docs_section += '<div  class="bs-docs-section"><div class="page-header">' +
            '<h1 style="" id="categorySection'+categories[i].id+'">'+categories[i].type+'</h1></div>' +
            '<div id="categoryTests'+categories[i].id+'" tag="'+categories[i].id+'"></div></div>';
    }
    $(".selectTestList").append(docs_section);
    $('.nav.bs-sidenav').append(nav_li);
    $('#dropdownCategory').html(li);
    $(".openTheTests").click(initializeTestList);
    $('.tag_category').append(tag_span);


    $('.tag_category>.tag>a').click(function () {
        var subject =$(".tag_subject > .tag.active >a").attr("tag");
        toPageTestList(subject,$(this).attr("tag"),1);
    });
}

/*dwr获取所有科目*/
function allSubject(subject) {
    var tag_span = '<span class="tag"><a href="javascript:void(0);" tag="0">不限</a></span>';
    var option = '<option value="" style="text-align: center" tag="0">' + '---------请选择---------' +
        '</option>';

    for (var i = 0; i < subject.length; i++) {
        tag_span = tag_span +
            '<span class="tag"><a href="javascript:void(0);" tag="' + subject[i].id + '">' + subject[i].subjectName + '</a></span>';
        option = option + '<option style="text-align: center" value="' + subject[i].subjectName +
            '" tag = "' + subject[i].id + '" >'
            + subject[i].subjectName + "</option>";

    }
    $('#subject').html(option);
    $('.tag_subject').append(tag_span);
    $('.tag_subject>.tag>a').click(function(){
        var category =$(".tag_category > .tag.active >a").attr("tag");
        toPageTestList($(this).attr("tag"),category,1);
    });

}

/*初始化选题列表*/
function initializeTestList() {
    $('#testsModal').modal('show');
    var chooseCategoryId = $(this).attr("tag");
    var chooseSubjectId = $("#testPaperSubject").attr("tag");
    toPageTestList(chooseSubjectId,chooseCategoryId,1);
}

var in_flag=0;
/*回调函数 返回页面数据*/
function getPageView(pageView) {
    var  pageChange = '<span style="color: #FFFFFF; margin: 5px;" >当前页:第'+pageView.currentPage+'页|总记录数'+pageView.totalRecord+'条|每页显条'+
        +pageView.maxResult+'条|总页数'+pageView.totalPage+'页 </span>';

    var pageNum = "";
    for(var i=pageView.pageIndex.startIndex;i<=pageView.pageIndex.endIndex;i++){
        if(pageView.currentPage == i){
            pageNum += '<span style="font-weight: bold;"><span style="color: #FFFFFF;margin-right: 4px; ">第'+
                i+'页 </span></span>';
        }else{
            pageNum +=
                '<a href="javascript:ajaxTopage('+ i +')" class="a03"><span ' +
                    'style="color: #FFFFFF;margin-right: 4px; ">第'+
                    i+'页 </span></a>';
        }

    }
    pageChange += pageNum;
    var pageRecord = "";
    if(pageView.totalRecord==0){
        pageRecord = '<tr><td style="width: 780px;text-align: center;" colspan="5">无数据</td></tr>';
    }else{
        for(i=0;i<pageView.records.length;i++){

            pageRecord += '<tr class="theTestsTr" id="theTestsTr' + pageView.records[i].id +'">';
            pageRecord+=
                '<td align="center" class="theFirstTd" style="width: 70px;"><div class="skin skin-square"><ul class="list"><li><input type="checkbox" id="square-checkbox-' + pageView.records[i].id+
                    '"  name="chooseTests" value="'+pageView.records[i].id+'"><label for="square-checkbox-'+pageView.records[i].id+'">'+'<div style="margin:15px 5px;">'+
                    '<span class="label label-warning" id="modal_testId' + pageView.records[i].id +'"  style="font-size: 80%;">'+ pageView.records[i].testId
                    +'</span></div></label></li></ul></div></td>';

            pageRecord+=' <td align="center" style="width: 30px;"><div style="margin:15px 0; ">'+
            '<span class="label label-primary" style="font-size: 85%;">'+pageView.records[i].category.type
            +'</span></div></td>';

            pageRecord+='<td align="center" style="width: 100px;">'
                +pageView.records[i].subject.subjectName+'</td>';

            pageRecord+='<td align="left" class="the_themes" id="modal_testTheme' + pageView.records[i].id +'" style="width: 400px;word-break:break-all;">'
                +pageView.records[i].theme+'</td>';

            if(pageView.records[i].category.type=='判断题'){
                pageRecord+='<td onclick="slideThePanel('+pageView.records[i].id+')" class="testAnswerTd" id="modal_testAnswer' + pageView.records[i].id +'" align="center" style="width: 200px;word-break:break-all;">';
                if("T"== pageView.records[i].answer.answer){
                    pageRecord+='说法正确';
                }
                else{
                    pageRecord+='说法错误';

                }
                pageRecord += '</td>';
            }else{
                pageRecord+='<td onclick="slideThePanel('+pageView.records[i].id+')" class="testAnswerTd" id="modal_testAnswer' + pageView.records[i].id +'"  align="center" style="width: 200px;word-break:break-all;">'
                +pageView.records[i].answer.answer+'</td>';
            }
            pageRecord += '</tr>';

            var answerKey;
            if(pageView.records[i].answer.answerKeys==null){
                answerKey="";
            }else{
                answerKey = pageView.records[i].answer.answerKeys;
            }

            pageRecord += '<tr class="panel" style="display:none;" id="testsPanel'+pageView.records[i].id+
            '" align="right">' + '<td align="right" style="width: 70px;">'+'<div style="margin:20px 5px; ">'+
            '<span class="label label-danger" style="font-size: 80%;margin-right: 10px;">难度</span>'+pageView.records[i].difficulty+
            '</div></td><td align="left" style="width: 30px;"></td><td align="left" style="width: 100px;"></td>'+
            '<td align="left" style="width: 400px;"><div style="margin:20px 0; "><span class="label label-danger" style="font-size: 80%;margin-right: 10px;">答案解析</span>'+
                answerKey +'</div></td><td align="left" style="width: 200px;"></td></tr>';


        }


    }
    $(".testsTable").html(pageRecord);
    $(".pageChange").html(pageChange);
    in_flag=0;
    $('.skin-square input').iCheck({
        checkboxClass: 'icheckbox_square-blue',
        radioClass: 'iradio_square-blue',
        increaseArea: '20%'
    });

    if(pageView.totalRecord>0){
        var addedTest = $("#categoryTests"+pageView.records[0].category.id).children("div");
        for(i=0;i<pageView.records.length;i++){
            for(var j=0;j<addedTest.length;j++){
                if(pageView.records[i].id == $(addedTest[j]).attr("tag")){
                    $("input[id^='square-checkbox-"+$(addedTest[j]).attr("tag")+"']").iCheck('check').iCheck('disable');
                }
            }
        }
    }



    $("input[id^='square-checkbox-']").on('ifChecked', function(){
        selectedTest += 1;
        $("#selectedTestNum").html(selectedTest);

    }).on('ifUnchecked', function(){
        selectedTest -= 1;

        $("#selectedTestNum").html(selectedTest);

    });


    $("input[id^='all-checkbox']").iCheck('uncheck');
    $('.allSelect input').on('ifChecked', function(){
        /*判断是否已添加*/
        var disable = $(".icheckbox_square-blue");
        var j=0;
        $("input[id^='square-checkbox-']").iCheck('check');
        for(i=1;i<disable.length;i++){
            if($(disable[i]).attr("class").indexOf("disabled")>0){
                $(disable[i]).addClass("checked");
                j++;
            }
        }
        if(in_flag==1){
            selectedTest -= j;
            in_flag=0;
            $("#selectedTestNum").html(selectedTest);
        }

    }).on('ifUnchecked', function(){
        /*判断是否已添加*/
        var disable = $(".icheckbox_square-blue");
        var j=0;
        $("input[id^='square-checkbox-']").iCheck('uncheck');
        for(i=1;i<disable.length;i++){
            if($(disable[i]).attr("class").indexOf("disabled")>0){
                $(disable[i]).addClass("checked");
                j++;
            }
        }
        if(in_flag==0){
            selectedTest += j;
            in_flag =1;
            $("#selectedTestNum").html(selectedTest);
        }


    });

}
function addTestToPage(){

    var score = $("#selectedTestScore").val();
    if("" == score.trim() || "0" == score.trim()){
        showMessage("提示","分数不能为0",'notice');
    }else{
        var selectTest = $("div[class $= 'checked'] ");
        var categoryTest = "";
        var testId = "";
        var category =$(".tag_category > .tag.active >a").attr("tag");
        var badge = $("#badge"+category);
        /*判断是否已添加*/
        var j=0;
        var i = 0;
        if($(selectTest[0]).children().val()=="-1"){
            i=1;
        }

        for(i;i<selectTest.length;i++){
            if($(selectTest[i]).attr("class").indexOf("disabled")<0){
                testId = $(selectTest[i]).children().val();
                categoryTest = '<h3 class="testHead'+testCount+'"> <small>第'+testCount+'题</small></h3><div id="tests'+ testId + '" class="everyTest" score="'+score+'"  tag="'+testId+'">' +
                    '<span class="label label-primary" id="delete'+testId+'" style="visibility: hidden; float: right;top:0;right: 0;background-color:#0066CC;font-size:15px;">' +
                    'x</span><div class="panel-body well well-lg" style="padding:20px;background-color: #F9F9F9;margin-bottom: 10px;" id="'+
                    testId+'"><span class="label label-primary" style="font-size: 85%;float: right;margin-left: 20px;padding: 5px;">题目编号:'+$("#modal_testId"+testId).html()+
                    '</span><div class="the_themes" style="word-break:break-all;">'+$("#modal_testTheme"+testId).html() +' </div><br/><div class="alert alert-success">'+
                    '<span class="label label-default" style="margin-bottom:15px;font-size: 85%; font-weight: bold;margin-right: 10px;">答案:</span>'+
                    $("#modal_testAnswer"+testId).html()+'</div></div></div></div>';

                $("#categoryTests"+category).append(categoryTest);
                $("#tests"+testId).mouseover(function(){
                    $(this).children("span[id^='delete']").css("visibility","visible");
                    $(this).children("div").css("border","2px solid #0066CC");
                }).mouseout(function(){
                    $(this).children("span[id^='delete']").css("visibility","hidden");
                    $(this).children("div").css("border","2px solid #F9F9F9");
                });

                $("#delete"+testId).mouseover(function(){
                    $(this).css("cursor","pointer");
                }).mouseout(function(){
                    $(this).css("cursor","default");
                }).click(function(){
                    testCount--;
                    $("#badge"+ $(this).parent().parent().attr("tag")).text((parseInt(badge.text())-1));
                    $(this).parent().remove();

                    scoreAndNum();
                });
                j++;
                testCount++;
            }

        }
        scoreAndNum();

        badge.text(parseInt(badge.text())+j);

        $('#testsModal').modal('hide');
    }


}

/*输出序号和分数*/
function scoreAndNum(){
    $("h3[class^='testHead']").remove();
    var category = $("div[id^='categoryTests']");
    var totalScore=0;
    var k=0;
    for(var i=0;i<category.length;i++){
        var categoryTag = $(category[i]).attr("tag");
        var allTestNum = $(category[i]).children("div");
        var categortScore=0;
        for(var j=0;j<allTestNum.length;j++){
            $('<h3 class="testHead'+(k+1)+'"> <small>第'+(k+1)+'题</small></h3>').prependTo(allTestNum[j]);
            var testScore = $(allTestNum[j]).attr("score");
            var testHead = $(".testHead"+(k+1));
            testHead.children("small").append("("+testScore+"分)");
            testHead.click(function(){
                var inputScore =  $(".inputTestScore");
                $(this).addClass("editScore");
                inputScore.attr("placeholder",$(this).parent().attr("score"));
                inputScore.val("");
                $(".editTestHead").html("编辑"+$(this).children("small").html().replace(/\(.+\)/g,"")+"分数");
                $('#editTestScore').modal('show').on('hidden.bs.modal', function () {
                    $(".editScore").removeClass("editScore");
                })
            }).mouseover(function(){
                $(this).css("cursor","pointer");
            }).mouseout(function(){
                $(this).css("cursor","default");
            });
            categortScore += parseInt(testScore);
            k++;
        }
        $(".categoryScore"+categoryTag).html("("+categortScore+"分)");

        totalScore += categortScore;
    }
    $("input[name='sumScore']").val(totalScore);
    $(".totalScore").html(totalScore+"分");
}

function editScoreButton(){
    var inputScore = $(".inputTestScore");
    if(""!=inputScore.val().trim()&&inputScore.val()!=inputScore.attr("placeholder")){
        var afterScore = parseInt(inputScore.val());
        $(".editScore").parent().attr("score",afterScore)
        scoreAndNum();
    }

}

function saveTestPaper(){
    var testNum = $(".everyTest");
    if(testNum.length<1){
        showMessage("保存失败","请添加试题",'error');
        return false;
    }
    if(""==$("#testPaperSubject").html().trim()){
        showMessage("保存失败","请添加科目",'error');
        return false;
    }
    var testIds ="";
    var testScores ="";
    for(var i=0;i<testNum.length;i++){
        testIds += $(testNum[i]).attr("tag")+",";
        testScores +=  $(testNum[i]).attr("score")+",";
    }
    testIds = testIds.substring(0,testIds.length-1);
    testScores = testScores.substring(0,testScores.length-1);

    $("input[name='testIds']").val(testIds);
    $("input[name='testScores']").val(testScores);

    return true;

}


/*题目列表点击下拉*/
function slideThePanel(panelId) {
    $("#testsPanel" + panelId).slideToggle("fast");
}
/*筛选条件按钮切换*/
function toggleSearchbutton() {
    $(".searchName").toggle();
    $(".tag-search").toggle();
}